package cn.whx.hrm.service;

import cn.whx.hrm.domain.LoginUser;
import cn.whx.hrm.domain.Permission;
import cn.whx.hrm.mapper.LoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetails implements UserDetailsService{
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        LoginUser user = loginUserMapper.selectOne(loginUser);
        if (user==null){
            throw new RuntimeException("该用户为空");
        }
        //用户存在 查询它的权限
        List<Permission> per =  loginUserMapper.getUserPermissionsById(user.getId());
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //查询出来的权限交给security管理
        per.stream().forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
            list.add(authority);
        });
        return new User(user.getUsername(),user.getPassword(),list);
    }

   /* public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = "1";
     *//*   String s1 = encoder.encode(password);
        System.out.println(s1);
        String s2 = encoder.encode(password);
        System.out.println(s2);*//*
        boolean b1 = encoder.matches(password, "$2a$10$aQ2vkBztprhWBsBSJU/sM.i3doosUE4MOSkXbjS/k9/TFwC5apsgi");
        boolean b2 = encoder.matches(password, "$2a$10$QwAN2keLg.Jwxf0U3OC82uuj5V4iqEtM.aL4nMR0mb8wRxCpjdDpK");
        System.out.println(b1);
        System.out.println(b2);
    }*/
}
